/**
 * Created by way on 16/9/28.
 */

import cfg from '../config';
const $ = require('../lib/kdom');
import {getView, get, post} from '../util/api';
// let _view = require('raw!./open.html');
let _view = '';

/* global txOName */
/* global txOMobile */
/* global dvOpen */
/* global btnOpen */
/* global liOpen */
/* global dvContainer */


const headUrl = 'https://im.icbc.com.cn/ICBCMPServer/servlet/ICBCGetAvailableImgPathServlet?dir=userinfo/';
let _us = [];
/*
const _us = [['白金香', '15161584615', '1049994228_poc'], ['白应梅', '18011111111', '1049994228_poc'],
  ['柏仁燕', '15816354851', '1049994228_poc'], ['包颜琳', '13513154899', '1049994228_poc'],
  ['鲍学梅', '18286479136', '1049994228_poc'], ['鲍  颖', '18024631478', '1049994228_poc'],
  ['蔡玲芳', '18631549875', '1049994228_poc'], ['蔡  艳', '18312345678', '1049994228_poc'],
  ['蔡  玉', '15800000000', '1049994228_poc'], ['曹发敏', '13712365487', '1049994228_poc']];
*/

let _run = false;
let _tm = null;
let _id = -1;
let _cnt = 0;
const _nd = 0; // 内定中奖,从最小奖开始，共10个名额
let _name = '';
let _mobile = '';

export default class {
  path = '/lottery/open$';
  hash = '/lottery/open';
  title = '幸运抽奖';
  constructor(opt) {
    opt = opt || {};
    this.path = opt.path || this.path;
    this.hash = opt.hash || this.hash;
    this.title = opt.title || this.title;
  }

  // 输出视图
  view(cb) {
    if (!_view) {
      // 静态资源浏览器有缓存,增加时标,强制刷新!
      getView(`${cfg.view.lotteryOpen}?t=${(+new Date())}`, '', (rs) => {
        _view = rs;
        cb(null, _view);
      });
    } else
      cb(null, _view);
  }

  // 在已经加载的视图上操作
  bind(dv, params) {
    // 页面组件 id 重名冲突，加载新页面，需卸载旧页面！！！
    const dx = $.id('pg-lottery-join');
    if (dx) {
      dvContainer.removeChild(dx);
    }

    _name = decodeURIComponent(params.name || '');
    _mobile = params.mobile || '';

    getUsers();
  }
}

function getUsers() {
  if (!_mobile) {
    return;
  }

  if (_us && _us.length > 0) {
    dvOpen.style.display = '';
  } else get(cfg.rel.lotteryGet, 'status=0', (rs) => {
    // alert(`getUsers rs:${rs}`);

    if (rs) {
      const r = JSON.parse(rs);
      if (r.rc === 200 && r.users && r.users.length > 0) {
        try {
          _us = r.users;
          dvOpen.style.display = '';
        } catch (e) {
          alert(e.message);
        }
      } else
        alert('获取数据失败，请在WIFI网络下重试!');
    }
  });
}

// 开始停止
window.open = () => {
  if (!_run) {
    if (_us && _us.length > 0) {
      _run = true;
      $.addClass(btnOpen, 'start');
      $.addClass($.qu('.zd_jindan'), 'zd_jindan01');
      btnOpen.style.display = 'none';
      $.html(btnOpen, '停 止 抽 奖');
      setTimeout(() => { btnOpen.style.display = ''; }, 100);
      start();
    } else
      alert('抽奖完毕');
  } else {
    _run = false;
    stop();
    win(_id); // 中奖

    $.html(btnOpen, '开 始 抽 奖');
    btnOpen.style.display = 'none';
    setTimeout(() => { btnOpen.style.display = ''; }, 100);
    $.removeClass(btnOpen, 'start');
    $.removeClass($.qu('.zd_jindan'), 'zd_jindan01');
    // set(_id); 未实现
  }
};

// 循环参加名单
function start() {
  if (!_us || !_us.length)
    return;

  const i = Math.floor(Math.random() * _us.length);
  txOName.value = _us[i][0];
  txOMobile.value = _us[i][1];
  _id = i;
  _tm = setTimeout(start, 0);
}

// 停止跳动
function stop() {
  clearInterval(_tm);
  _tm = null;
}

function set(id) {
  post(cfg.rel.set, `mobile=${_us[id][1]}&status=1`, (rs) => {
    if (rs) {
      const r = JSON.parse(rs);
/*
      if (r.rc !== 200) {
        alert('');
      }
*/
    }
  });
}

// 从一等奖开始指定前3名
function win(id) {
  _cnt ++;

  if (_nd === 0) {
    // 打印中奖者名单
    let mb = _us[id][1]; //.replace(/(\d{3}\d{4}(\d+))/, '$1xxxx$2');
    mb = `${mb.substr(0, 3)}****${mb.substr(7)}`;
    txOMobile.value = mb;
    const li = $.dc(null, 'li');
    $.html(li, `<li><div class="item-content"><div class="item-inner">
<div class="item-title label">${_cnt}、${_us[id][0]}</div>
<div class="item-info">${mb}</div></div></div></li>`);
    liOpen.parentNode.insertBefore(li, liOpen);

    // 将已中奖者从数组中"删除",防止二次中奖
    _us.splice(id, 1);
  }

/*
  if (_nd <= 3){
    if (td == 1) {
      nametxt.html('周一一');
      phonetxt.html('15112345678');
      $('.list').prepend("<p>"+td+' '+"周一一 -- 15112345678</p>");
    }
    if (td == 2) {
      nametxt.html('李二二');
      phonetxt.html('151000000000');
      $('.list').prepend("<p>"+td+' '+"李二二 -- 151000000000</p>");
    }
    if (td == 3) {
      nametxt.html('张三三');
      phonetxt.html('1511111111');
      $('.list').prepend("<p>"+td+' '+"张三三 -- 1511111111</p>");
    }
  }
*/
}
